package com.ten.mall.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ten.mall.service.AddressService;
import com.ten.mall.vo.Address;
import com.ten.mall.vo.User;


@Controller
public class AddressControlller {
	@Autowired
	private AddressService addressService;
	@RequestMapping("/phone/addressList")
	public String toAddress(HttpServletRequest res){
		User user =(User) res.getSession().getAttribute("u");
		Address  address =addressService.selectByState(user.getId(), null);
		res.setAttribute("address", address);
		return "phone/address_list";
	}
	/**
	 * 订单处修改地址
	 * @param res
	 * @param orderId
	 * @param addressId
	 * @return
	 */
	@RequestMapping("/phone/addressEdit")
	public String toAddressEdit(HttpServletRequest res,String orderId,Integer addressId){
		if(addressId!=null){
			Address add =addressService.selectById(addressId);
			res.setAttribute("app", add);
		}
		res.setAttribute("orderId", orderId);
		return "phone/shop_address";
	}
	/**
	 * 用户中心修改地址
	 * @param res
	 * @param addressId
	 * @return
	 */
	@RequestMapping("/phone/addressUserEdit")
	public String userEditAddress(HttpServletRequest res,Integer addressId){
		Address add =addressService.selectById(addressId);
		res.setAttribute("app", add);
		return "phone/user_address";
	}
	@RequestMapping("/phone/saveAddress")
	public String saveAddress(Address address,HttpServletRequest res,String orderId){
		User u =(User) res.getSession().getAttribute("u");
		String result="redirect:/phone/toOrder?id="+orderId;
		try {
			if(address.getId()==null){
				if(u!=null){
					address.setUserId(u.getId());
				}
				addressService.insertAddress(address);
			}else{
				addressService.updateAddress(address);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(StringUtils.isBlank(orderId)){
			result="redirect:/phone/userInfo";
		}
		return result;
	}
	
	@RequestMapping("/phone/editSaveAddress")
	public String editAddress(Address address,HttpServletRequest res,String url){
		addressService.updateAddress(address);
		String[] array =url.split("_");
		String rUrl="/phone/toOrder?id="+array[0]+"&paySum="+array[1];
		System.out.println("rUrl:"+rUrl);
		return "redirect:"+rUrl;
	}
	@RequestMapping("/phone/getAddress")
	@ResponseBody
	public Address getAddressDefault(HttpServletRequest res){
		User u =(User) res.getAttribute("u");
		Address address =addressService.selectByState(u.getId(), 1);
		return address;
	}
}
